<template>
  <div class="add">
    <el-row :gutter="15" class="box">
      <el-col :span="12">
        <section class="original-text">
          <hgroup><i class="el-icon-picture"></i> 原文信息</hgroup>
          <div v-if="type === 'add'">
            <div class="btn-box">
              <!---->
              <el-upload
                class="upload-btn"
                ref="upload"
                action="#"
                :on-change="handlePreview"
                :file-list="fileList"
                :limit="1000"
                accept=".jpg,.jpeg,.png"
                multiple
                list-type="picture"
                :show-file-list="false"
                :auto-upload="false">
                <el-button slot="trigger" @click="showOcrText = false" class="open-btn" size="mini">打开</el-button>
              </el-upload>

              <el-button size="mini" @click="showOcrText = true" class="ocr-btn">ocr识别后内容</el-button>
            </div>
            <div class="original">
              <ul v-show="!showOcrText">
                <li v-for="(item, index) in fileList" :key="index">
                  <img :src="item.url" alt=""/>
                  <div class="btn-function">
                    <el-button size="mini"
                               @click="handleOcr(item, index)"
                               class="ocr-btn"
                               :loading="item.loading"
                               style="margin-right: 10px">ocr识别图片内容
                    </el-button>
                    <i class="el-icon-full-screen full-screen" @click="handleFullScreen(item.url)"></i>
                    <i class="el-icon-close romve" @click="handleRemove(item)"></i>
                  </div>
                </li>
              </ul>

              <!--ocr识别后的内容-->
              <div class="ocr-text" v-show="showOcrText">
                {{ocrText}}
              </div>

            </div>

            <xzf-dialog v-if="dialogVisible"
                        :dialogImageUrl="dialogImageUrl"
                        @xzfClose="handleCloseDialog">
            </xzf-dialog>

          </div>
          <div v-else>
            <el-tabs type="border-card" @tab-click="handleTabClick">
              <el-tab-pane label="原文展示">
                <div class="pdf-box">
                  <pdf-js-iframe :url="pdfSrc" :fileName="rowData.dh + '.pdf'"></pdf-js-iframe>
                </div>
              </el-tab-pane>

              <el-tab-pane label="列表">
                <div class="btn-center">
                  <!--accept=".jpg,.jpeg,.png,.mp3,.mp4,.docx"-->
                  <el-upload
                    class="upload-btn"
                    ref="upload"
                    :action="action"
                    :headers="headers"
                    :on-change="handlePreview"
                    :file-list="fileList"
                    :limit="1000"
                    multiple
                    list-type="picture"
                    :show-file-list="false"
                    :auto-upload="false">
                    <el-button slot="trigger" type="primary" @click="showOcrText = false" class="open-btn" size="mini">
                      上传原文
                    </el-button>
                  </el-upload>
                  <el-button size="mini" type="primary" @click="handlePdfSrc">生成pdf</el-button>
                  <el-button size="mini" type="primary" @click="handleOcrList">ocr识别</el-button>
                  <el-button size="mini" type="danger" @click="handleDel">删除</el-button>
                </div>
                <avue-crud :option="option"
                           :table-loading="tableLoading"
                           :data="tableData"
                           :page.sync="page"
                           ref="crud"
                           @on-load="onLoad"
                           @selection-change="selectionChange"
                >
                  <template slot-scope="scope" slot="menu">
                    <el-button icon="el-icon-view"
                               @click="handleRead(scope.row)"
                               type="text">查看</el-button>
                    <el-button icon="el-icon-download"
                               @click="handleDownload(scope.row)"
                               type="text">下载</el-button>
                  </template>
                </avue-crud>
              </el-tab-pane>

              <el-tab-pane label="ocr识别后内容">

                <!--                <el-button size="mini">ocr校验</el-button>-->
                <div v-loading="tableLoading">
                  <vue-ueditor-wrap class="editer"
                                    v-model="msg"
                                    :config="myConfig"></vue-ueditor-wrap>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>

        </section>
      </el-col>
      <el-col :span="12">
        <section class="add-form">
          <hgroup><i class="el-icon-edit-outline"></i> 录入信息</hgroup>

          <avue-form ref="form"
                     class="add-body"
                     v-model="obj"
                     :option="options"
                     @submit="submit">
            <template slot-scope="scope" slot="qzh">
              <el-select v-model="obj[scope.column.prop]"
                         :disabled="ajId !== ''"
                         @change="handleQzh">
                <el-option v-for="(item, index) in scope.column.dicData"
                           :key="index"
                           :value="item.fondsNo"
                           :label="item.fondsNo + ' ' + item.fondsName"></el-option>
              </el-select>
            </template>
          </avue-form>
          <div class="add-btn">
            <el-button type="primary" :loading="loading" size="small" @click="handleAdd">保存</el-button>
            <el-button type="primary"
                       :loading="loading"
                       size="small"
                       v-if="type === 'add'"
                       @click="handleSaveAdd">存加</el-button>
          </div>
        </section>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import {
  addElectronicsFile, addSaveData, delYuanwenList, downloadPdfOriginal,
  editElectronicsFile, getOriginalImgList, getPdfOriginal,
  hookUpText, requestGeneratePdf, requestOCRService
} from '../../../../../../api/electronicsFile/electronicsFile'
import XzfDialog from '../../../../../../components/xzfDialog/xzfDialog'
import { ocrDistinguish } from '../../../../../../api/ocr'
import { mapActions } from 'vuex'
import VueUeditorWrap from 'vue-ueditor-wrap'
import { getObjectURL } from '../../../../../../util/util'
import { mapFields } from 'vuex-map-fields'
import { getDepartmentList } from '../../../../../../api/department/department'
import { getClassificationTreeForm } from '../../../../../../api/classification'
import PdfJsIframe from '../../../../../../components/showPdf/pdfJsIframe'

export default {
  name: 'addElectronicsArchives',
  components: {
    PdfJsIframe,
    XzfDialog,
    VueUeditorWrap
  },
  props: {
    fmtJson: {
      type: Array,
      default: () => ([])
    },
    idTable: {
      type: String
    },
    ajId: {
      type: String,
      default: ''
    },
    idCategory: {
      type: String,
      default: ''
    },
    type: {
      request: true,
      type: String
    },
    formOptions: {
      // 表单
      type: Object,
      default: () => ({})
    },
    rowData: {
      type: Object
    },
    ajRowData: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      saveType: 'save',
      bumenList: [], // 部门下拉框数据
      dialogVisible: false,
      dialogImageUrl: '',
      isShow: 'isPdf',
      loading: false,
      obj: {
        qzh: ''
      },
      fileList: [],
      editFileList: [], // 修改时上传的原文
      imgScale: 1,
      showOcrText: false,
      ocrText: '',
      pdfSrc: '',
      action: '#',
      headers: {},
      tableLoading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        pageSizes: [20, 40, 60, 80],
        total: 0
      },
      tableData: [],
      yuanwenSelectList: [], // 原文列表选中项
      option: {
        align: 'center',
        menuAlign: 'center',
        header: false,
        border: true,
        size: 'medium',
        height: 'calc(100vh - 260px)',
        index: true, // 显示序号
        indexLabel: '序号', // 显示序号
        selection: true, // 多选
        editBtn: false, // 行内编辑按钮
        delBtn: false, // 行内删除按钮
        viewBtn: false, // 行内查看按钮
        // menu: false,
        menuWidth: 135,
        column: [
          {
            label: '文件名',
            prop: 'fileName',
            overHidden: true
          },
          {
            label: '路径',
            prop: 'filePath',
            overHidden: true
          }
        ]
      },
      // 富文本
      msg: '',
      myConfig: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 240,
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
        serverUrl: '',
        // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
        UEDITOR_HOME_URL: './UEditor/'
      }
    }
  },
  mounted () {
    if (this.type === 'add') {
      this.saveAddRequest(this.rowData.id)
    } else {
      const row = JSON.stringify(this.rowData)
      this.obj = JSON.parse(row)
      this.getBumen()
    }
    this.setUpload()
  },
  watch: {
    rowData: {
      handler: () => {
        if (this.type === 'add') {
          this.$refs.form.resetForm()
          this.saveAddRequest(this.rowData.id)
        } else {
          const row = JSON.stringify(this.rowData)
          this.obj = JSON.parse(row)
          this.setUpload()
          this.getBumen()
        }
      },
      deep: true
    }
  },
  computed: {
    ...mapFields('profile/profile', {
      userInfo: 'retrieved'
    }),
    ...mapFields('electronicsFile/setSearchCondition', {
      searchParams: 'retrieved'
    }),
    options () {
      const form = {}
      if (this.formOptions && this.formOptions.column && this.formOptions.column.length > 0) {
        Object.keys(this.formOptions).forEach(key => {
          if (key !== 'column') {
            form[key] = this.formOptions[key]
          } else {
            form.column = []
            this.formOptions.column.map((item, index) => {
              form.column.push(item)
              this.fmtJson.map((dhgz) => {
                if (dhgz.column === item.prop) {
                  form.column[index].rules = [{
                    required: true,
                    message: '请输入' + dhgz.name,
                    trigger: 'blur'
                  }]
                }
              })
              if (item.prop === 'zldw') {
                form.column[index].dicData = this.bumenList
                form.column[index].disabled = this.ajId !== ''
              }
              if (item.prop === 'ajdh') {
                form.column[index].disabled = true
              }
              if (item.prop === 'flh') {
                form.column[index].dicData = this.flhTree
                form.column[index].type = 'tree'
                form.column[index].props = {
                  label: 'categoryName',
                  value: 'classificationCode',
                  children: 'children'
                }
              }
            })
          }
        })
        form.column.map(item => {
          if (item.prop === 'dh') {
            const dhguize = []
            this.fmtJson.map((dhgz, index) => {
              if (this.obj[dhgz.column]) {
                if (dhgz.column === 'zldw') {
                  this.bumenList.map(item => {
                    if (item.id === this.obj[dhgz.column]) {
                      dhguize[index] = item.orgCode
                    }
                  })
                } else {
                  dhguize[index] = this.obj[dhgz.column]
                }
                if (Number(dhgz.length) > (this.obj[dhgz.column] + '').length) {
                  dhguize[index] = '0000000000'.substr(0, Number(dhgz.length) - (this.obj[dhgz.column] + '').length) + '' + this.obj[dhgz.column]
                }
                dhguize[index] = dhguize[index] + dhgz.separator
              }
            })
            if (this.type === 'add') {
              this.obj.dh = dhguize.join('')

              const arr = JSON.parse(JSON.stringify(dhguize))
              if (dhguize.length > 1) {
                this.obj.ajdh = arr.slice(0, dhguize.length - 1).join('')
              } else {
                this.obj.ajdh = arr.join('')
              }
              this.obj.ajdh = this.obj.ajdh.replace(/-$/gi, '')
            }
          }
        })
      }

      return form
    }
  },
  methods: {
    ...mapActions('electronicsFile/getHead', ['getTableList']),
    getOriginalText () {
      getPdfOriginal(this.idTable, this.rowData.id).then(res => {
        // 请求pdf流文件后转vue-pdf预览用的src
        this.pdfSrc = getObjectURL(res.data)
      })
    },
    handleQzh () {
      this.obj.zldw = ''
      this.getBumen()
    },
    getBumen () {
      // 根据全宗查部门
      if (this.ajId !== '') {
        this.obj.qzh = this.ajRowData.qzh
        this.obj.zldw = this.ajRowData.zldw || this.userInfo.idOrg
        this.obj.ajdh = this.ajRowData.ajdh
      }
      const query = {
        pageSize: 1000,
        pageNo: 1,
        params: [{
          name: 'fondsNo',
          op: 'eq',
          value: this.obj.qzh
        }]
      }
      getDepartmentList(query).then(res => {
        this.bumenList = res.data.data.list
      })

      // 根据全宗和门类查分类号
      let qzId = ''
      this.options.column.map(item => {
        if (item.prop === 'qzh') {
          item.dicData.map(qz => {
            if (qz.fondsNo === this.obj.qzh) {
              qzId = qz.id
            }
          })
        }
      })
      const flhQuery = {
        idCategory: this.idCategory
      }
      if (qzId) {
        flhQuery.fondsNoId = qzId
      }
      getClassificationTreeForm(flhQuery).then(res => {
        this.flhTree = res.data.data
      })
    },
    setUpload () {
      if (this.type === 'edit') {
        this.getOriginalText()
      }
    },
    handleTabClick (val) {
      if (val.label === '原文展示') {
        this.getOriginalText()
      }
      if (val.label === 'ocr识别后内容') {
        this.onLoad()
      }
    },
    onLoad () {
      // 加载列表
      this.tableLoading = true
      const query = {
        pageSize: this.page.pageSize,
        pageNo: this.page.currentPage,
        params: [{
          op: 'eq',
          name: 'id_record',
          value: this.rowData.id
        }]
      }
      getOriginalImgList(this.idTable, query).then(res => {
        this.tableData = res.data.data.records
        this.page.total = res.data.data.total
        this.tableLoading = false
        this.msg = ''
        this.tableData.map(item => {
          this.msg += '<div>' + item.ocrText + '</div>'
        })
      })
    },
    handleFullScreen (url) {
      this.dialogImageUrl = url
      this.dialogVisible = true
    },
    handleCloseDialog () {
      this.dialogVisible = false
    },
    handleRemove (file, fileList) {
      if (this.fileList.indexOf(file) > -1) {
        this.fileList.splice(this.fileList.indexOf(file), 1)
      }
    },
    handlePreview (file) {
      if (file.raw.type === 'image/jpeg' || file.raw.type === 'image/png') {
        this.fileList.push(file)
      } /* else {
        this.$message.warning('暂时只支持上传图片！')
        return
      } */
      if (this.type === 'edit') {
        this.editFileList.push(file)
        const formData = new FormData()
        this.editFileList.map(item => {
          formData.append('files', item.raw)
        })
        hookUpText({
          idTable: this.idTable,
          arcId: this.obj.id
        }, formData).then(() => {
          this.$message.success('上传文件成功！')
          this.onLoad()
        })
        this.editFileList = []
      }
    },
    handleOcr (item, index) {
      // ocr识别]
      const obj = item
      obj.loading = true
      this.$set(this.fileList, index, obj)
      const formData = new FormData()
      formData.append('file ', item.raw)
      ocrDistinguish(formData).then(res => {
        this.ocrText = res.data.data
        this.$message.success('ocr识别成功！')
        obj.loading = false
        this.$set(this.fileList, index, obj)
      }).catch(() => {
        obj.loading = false
        this.$set(this.fileList, index, obj)
      })
    },
    handleAdd () {
      // 保存
      this.saveType = 'save'
      this.$refs.form.submit()
    },
    handleSaveAdd () {
      // 存加
      this.saveType = 'saveAdd'
      this.$refs.form.submit()
    },
    saveAddRequest (idRec) {
      this.obj.qzh = this.userInfo.fonsNo
      this.getBumen()
      const idRecObj = idRec ? { idRec: idRec } : {}
      addSaveData(this.idTable, idRecObj).then(res => {
        Object.keys(this.obj).forEach(key => {
          if (key === 'zldw') {
            this.obj.zldw = this.userInfo.idOrg
          } else if (key === 'qzh') {
            this.obj.qzh = this.userInfo.fonsNo
          } else {
            this.obj[key] = ''
            if (res.data.data && res.data.data[key] !== 'null') {
              this.obj[key] = res.data.data[key]
            }
          }
        })
      })
    },
    submit (form, done) {
      // 保存提交
      this.loading = true
      if (this.type === 'add') {
        form.gdbs = 3
        if (this.ajId) {
          form.id_aj = this.ajId
        }
      }
      const requestFun = this.type === 'add' ? addElectronicsFile({
        idTable: this.idTable,
        addType: 1,
        data: form
      }) : editElectronicsFile(this.idTable, {
        arcId: this.obj.id,
        data: form
      })

      requestFun.then((res) => {
        this.$message.success(this.type === 'add' ? '新增成功！' : '修改成功！')
        if (this.type === 'add') {
          const param = {
            pageNo: 1,
            pageSize: 20,
            params: this.searchParams
          }
          this.getTableList({
            idTable: this.idTable,
            data: param
          })
        }
        this.loading = false
        if (this.type === 'add' && this.fileList.length > 0) {
          this.$confirm('是否上传文件?', '提示', {
            confirmButtonText: '确定上传文件',
            cancelButtonText: '不上传文件',
            type: 'warning'
          }).then(() => {
            // 挂接原文
            const formData = new FormData()
            this.fileList.map(item => {
              formData.append('files', item.raw)
            })
            hookUpText({
              idTable: this.idTable,
              arcId: res.data.data
            }, formData).then(() => {
              this.$message.success('挂接原文成功！')
              if (this.saveType === 'save') {
                this.$emit('handleAddSuccess')
              }
            })
          }).catch(() => {
            if (this.saveType === 'save') {
              this.$emit('handleAddSuccess')
            }
          })
        } else {
          if (this.saveType === 'save') {
            this.$emit('handleAddSuccess')
          }
        }

        if (this.saveType === 'saveAdd') {
          this.saveAddRequest(res.data.data)
        }

        if (this.type === 'edit') {
          this.$emit('handleAddSuccess')
        }

        done()
      }).catch(() => {
        this.loading = false
        done()
      })
    },
    selectionChange (list) {
      // 勾选原文
      this.yuanwenSelectList = list
    },
    handlePdfSrc () {
      // 生成pdf
      requestGeneratePdf(this.idTable, this.rowData.id).then(() => {
        this.$message.success('生成pdf成功！')
      })
    },
    handleOcrList () {
      // ocr识别服务器上面的图片
      if (this.yuanwenSelectList.length !== 1) {
        this.$message.warning('ocr只能识别单张原文图片！')
        return
      }
      requestOCRService(this.idTable, this.yuanwenSelectList[0].id).then(() => {
        this.$message.success('ocr识别成功！')
      })
    },
    handleDel () {
      // 删除原文
      if (this.yuanwenSelectList.length < 1) {
        this.$message.warning('请勾选需要删除的原文！')
      } else {
        this.$confirm('此操作将永久删除该选中信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const data = { ids: [] }
          this.yuanwenSelectList.map(item => {
            data.ids.push(item.id)
          })
          delYuanwenList(this.idTable, data).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.onLoad()
          })
        })
      }
    },
    handleRead (row) {
      // 查看图片
      downloadPdfOriginal(this.idTable, row.id).then(res => {
        const fileType = res.headers['content-type']
        const blob = new Blob([res.data], { type: fileType }) // 构造一个blob对象来处理数据

        window.open(URL.createObjectURL(blob), row.fileName)
      })
    },
    handleDownload (row) {
      // 下载原文
      downloadPdfOriginal(this.idTable, row.id).then(res => {
        const fileType = res.headers['content-type']
        const blob = new Blob([res.data], { type: fileType }) // 构造一个blob对象来处理数据
        const fileName = row.fileName

        // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
        // IE10以上支持blob但是依然不支持download
        if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
          const link = document.createElement('a')// 创建a标签
          link.download = fileName// a标签添加属性
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click()// 执行下载
          URL.revokeObjectURL(link.href) // 释放url
          document.body.removeChild(link)// 释放标签
        } else { // 其他浏览器
          navigator.msSaveBlob(blob, fileName)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .box {
    height: 100%;
    padding: 0 10px;

    .original-text {
      height: 100%;
      overflow-y: auto;
      border: 1px solid #DCDFE6;

      hgroup {
        background: #ddd;
        line-height: 40px;
        padding: 0 12px;
        color: #333;
      }

      .original {
        height: calc(100vh - 160px);
        overflow-y: auto;
        margin-top: 5px;
        padding: 0 5px;

        li {
          margin: 10px 0;
          border: 1px solid #ddd;
          position: relative;
          text-align: center;

          &:hover {
            .btn-function {
              display: flex;
            }
          }

          .btn-function {
            position: absolute;
            top: 5px;
            right: 5px;
            cursor: pointer;
            display: none;
            justify-content: space-between;
            align-items: center;
            ont-size: 24px;

            i.romve {
              font-size: 20px;
              margin-left: 5px;
            }

            i:hover {
              opacity: 0.8;
            }
          }
        }

        img {
          max-width: 100%;
        }
      }

      .ocr-text {
        padding: 20px;
      }

      .big-img {
        max-height: calc(100vh - 100px);
        overflow: auto;

        img {
          max-width: calc(100vw - 100px);
          transition: 0.4s linear;
        }
      }

      .btn-box {
        position: relative;

        .ocr-btn {
          position: absolute;
          top: 10px;
          left: 75px;
        }

        .upload-btn {
          padding-top: 10px;

          .open-btn {
            margin-left: 10px;
          }
        }
      }

    }

    .btn-center {
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .upload-btn {
        margin-right: 10px;
      }
    }

    .add-form {
      border: 1px solid #DCDFE6;

      hgroup {
        background: #ddd;
        line-height: 40px;
        padding: 0 12px;
        color: #333;
      }

      .title {
        color: #333;
        font-weight: bolder;
      }

      .add-body {
        height: calc(100vh - 148px);
        overflow-y: auto;
        padding-top: 15px;

        ::v-deep .el-card__body {
          padding: 0 20px 0 0;
        }

        ::v-deep .el-form-item {
          margin-bottom: 20px;
        }

        .inline {
          display: flex;
          justify-content: space-between;
        }
      }

      .add-btn {
        text-align: right;
      }
    }

    ::v-deep .el-tabs--border-card {
      border: none;

      .el-tab-pane {
        height: calc(100vh - 182px);
        overflow-y: auto;
      }
    }

    .show-pdf {
      height: calc(100% - 30px);
    }
  }

  .pdf-box {
    height: 100%;
  }

  .upload-demo {
    text-align: center;
  }

  .editer {
    height: calc(100% - 30px);

    ::v-deep #editor_rijvoefj, ::v-deep .edui-editor {
      height: 100%;
    }

    ::v-deep .edui-editor-iframeholder.edui-default {
      height: calc(90vh - 300px) !important;
    }
  }
</style>
